<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/3/20
 * Time: 11:46
 */

namespace app\queue\generatedwork;

use app\common\lib\Common;
use app\common\lib\Constant;
use app\common\lib\DetectFaceAdvance;
use app\common\lib\Guzzle;
use app\common\lib\MoyinTts;
use app\common\lib\RedisQueue;
use app\common\lib\TencentTts;
use app\exception\IndexException;
use app\model\consume\ConsumePointLogModel;
use app\model\image\ImageModelModel;
use app\model\novel\NovelChapterModel;
use app\model\novel\NovelChapterPartModel;
use app\model\plan\PromotionPlanModel;
use app\model\plan\PromotionPlanPartImageModel;
use app\model\queue\AiImageRequestQueueModel;
use app\model\redis\RedisQueueModel;
use app\model\tencent\TimbreModel;
use app\model\user\UserNovelChapterPartModel;
use app\model\user\UserPointFlowModel;
use app\model\user\UserPromotionPlanModel;
use app\model\novel\NovelPlanRoleModel;
use support\Cache;
use support\Db;
use Webman\RedisQueue\Consumer;
use app\common\lib\TencentCos;

class AsyncGeneratedVideoData  implements Consumer
{
    // 要消费的队列名
    public $queue = 'asyncGeneratedVideoData';

    // 连接名，对应 plugin/webman/redis-queue/redis.php 里的连接`
    public $connection = 'default';

    protected $resultData = [];

    // 消费
    public function consume($data)
    {
        Common::initQueueConfig();

        $queue = RedisQueueModel::getInstance()->find($data['queueid']);
        $queue->exec_time = date('Y-m-d H:i:s');
        $queue->save();

        try{
            // 无需反序列化
            $result = $this->handle($data);

            RedisQueue::getInstance()->saveQueue($this->queue,$data,$result);
        }catch (IndexException $e){
            //生成失败处理
            $this->generatedFail($data,$e);

            RedisQueue::getInstance()->saveQueue($this->queue,$data,['error'=>$e->getMessage()]);
            Common::queueExecptionReport($queue,$data,$e);
        }catch (\Throwable $e){
            //生成失败处理
            $this->generatedFail($data,$e);

            RedisQueue::getInstance()->saveQueue($this->queue,$data,['error'=>$e->getMessage()]);
            Common::queueExecptionReport($queue,$data,$e);
        }
    }

    protected function handle($data)
    {
        //todo 1 加入队列状态变更
        $userPlan = UserPromotionPlanModel::getInstance()->find($data['user_planid']);
        $userPlan->queue_time = date('Y-m-d H:i:s');
        $userPlan->status = 1;
        $userPlan->message = '生成中';
        $userPlan->save();

        //todo 2 生成创作内容片段-配音
        $requestId = $this->generatedTimbre($data);

        //todo 3 生成创作内容片段-ai漫画
        if(in_array($userPlan['plan_type'],[1,2,3])){
            $this->generatedDescAndAIImage($data);
        }

        //todo 4 执行完成状态变更-延迟1秒在读取状态
        sleep(1);
        $isFinish = 1;
        $userPlanParts = UserNovelChapterPartModel::getInstance()->getWhere(['user_planid'=>$data['user_planid']])->orderBy('number','asc')->get();
        foreach ($userPlanParts as $val){
            if(empty($val['timbre_voice_url'])){
                $isFinish = 2;
                break;
            }
            if(in_array($userPlan['plan_type'],[1,2,3])){
                if(empty($val['ai_images']) || empty($val['ai_images_arr'])){
                    $isFinish = 3;
                    break;
                }
            }
        }

        if($isFinish===1){
            $userPlan = UserPromotionPlanModel::getInstance()->find($data['user_planid']);
            $userPlan->finish_time = date('Y-m-d H:i:s');
            $userPlan->status = 2;
            $userPlan->message = '生成成功';
            $userPlan->save();
        }elseif($isFinish===2){
            $n=0;
            //等待配音完成
            while (true){
                $status = RedisQueueModel::getInstance()->getWhere(['name'=>'generateTimbre',['data','like',"%{$requestId}%"]])->value('status');
                if($status==2){
                    throw new IndexException(4020,'作品配音合成失败');
                }elseif($status==1){
                    $userPlan = UserPromotionPlanModel::getInstance()->find($data['user_planid']);
                    $userPlan->finish_time = date('Y-m-d H:i:s');
                    $userPlan->status = 2;
                    $userPlan->message = '生成成功';
                    $userPlan->save();
                    break;
                }
                if($n>600){
                    throw new IndexException(4020,'作品配音合成超时');
                }
                $n++;
                sleep(1);
            }
        }elseif($isFinish===3){
            throw new IndexException(4020,'作品AI生图失败');
        }

        return ['success'];
    }

    protected function generatedTimbre($data)
    {
        //队列名
        $queue = 'generateTimbre';
        $requestId = Common::getRequestId();

        // 数据，可以直接传数组，无需序列化
        $data = ['requestid'=>$requestId, 'user_planid'=>$data['user_planid'], 'source'=>'generate_work'];

        // 投递消息
        RedisQueue::getInstance()->sendQueue($queue, $data);

        return $requestId;
    }

    protected function generatedDescAndAIImage($data)
    {
        $userPlan = UserPromotionPlanModel::getInstance()->find($data['user_planid']);
        if($userPlan==false){
            throw new IndexException(4020,'用户方案不存在');
        }
        $aiImageCommands = json_decode($userPlan['ai_image_command'], true);
        if($aiImageCommands==false){
            throw new IndexException(4020,'生图指令JSON格式错误');
        }
        $modelVal = $aiImageCommands['override_settings']['sd_model_checkpoint']??'';
        if($modelVal==false){
            throw new IndexException(4020,'模型不能为空');
        }
        $imageNums = $userPlan['ai_images_nums']??1;
        $aiImageCommand = $userPlan['ai_image_command']??'';

        $width = 1024;
        $height = 1024;

        $userPlanParts = UserNovelChapterPartModel::getInstance()->getWhere(['user_planid'=>$data['user_planid']])->orderBy('number','asc')->get();

        //如果类型是漫画推文和视频二创，则需要批量生成英文描述词
        if(in_array($userPlan['plan_type'],[2,3])){
            $contentDatas = [];
            foreach ($userPlanParts as $val){
                if(empty($val['prompt'])){
                    $contentDatas[] = ['id'=>$val['id'],'content'=>$val['content']];
                }
            }

            if(!empty($contentDatas)){
                $contentTextChunks = array_chunk($contentDatas,50);
                foreach ($contentTextChunks as $contentTexts){
                    $n=1;
                    while (true){
                        $contentData = [];
                        foreach ($contentTexts as $k=>$contents){
                            $contentData[] = (($k+1).'.').preg_replace('/^\d+[\.]+/','',$contents['content']);
                        }
                        $contentText = implode("\n",$contentData);
                        $promptContent = Common::generatedBatchPrompt($contentText);

                        $promptContents = array_values(array_filter(explode("\n",$promptContent)));
                        if(count($promptContents)==count($contentTexts)){
                            foreach ($contentTexts as $k=>$contents){
                                if(isset($promptContents[$k])){
                                    //黑名单词过滤
                                    $aiCommandBlackListWorks = array_filter(explode('|@@|',config('param.ai_command_blacklist_works','')));
                                    $pregs = [];
                                    foreach($aiCommandBlackListWorks as $word){
                                        $pregs[] = ' '.ucfirst(trim($word)).' ';
                                        $pregs[] = ' '.lcfirst(trim($word)).' ';
                                    }
                                    $promptContent = str_replace($pregs,' ',$promptContents[$k]??'');

                                    $promptContent = preg_replace('/^\d+[\.]+/','',$promptContent);

                                    UserNovelChapterPartModel::getInstance()->getWhere(['id'=>$contents['id']])->update(['prompt'=>$promptContent]);
                                }
                            }
                            //满足就跳出
                            break;
                        }
                        if($n>=3){
                            break;
                        }
                        $n++;
                        sleep(1);
                    }
                }

                //重新在读取一次
                $userPlanParts = UserNovelChapterPartModel::getInstance()->getWhere(['user_planid'=>$data['user_planid']])->orderBy('number','asc')->get();
            }
        }


        $requestIdMap = [];
        foreach ($userPlanParts as $val){
            if(!empty($val['ai_images']) || !empty($val['ai_images_arr'])){
                continue;
            }
            //20240819 拿提前生成好的图，如有就跳过
            if(!empty($val['partid'])){
                $where = [
                    'partid'=>$val['partid'],
                    'status'=>1,
                ];
                $imageData = PromotionPlanPartImageModel::getInstance()->getWhere($where)->limit($imageNums)->get();
                $images = [];
                $aiImagFaceArrs = [];
                foreach ($imageData as $image){
                    $images[] = $image['ai_image'];
                    $aiImagFaceArr = $image['ai_image_face_arr'] ? json_decode($image['ai_image_face_arr'],true)[0] :[];
                    $aiImagFaceArr && $aiImagFaceArrs = array_merge($aiImagFaceArrs,$aiImagFaceArr);
                }
                if(count($images)==$imageNums){
                    $update = [];
                    $update['ai_images_bak'] = $images[0];
                    $update['ai_images_arr_bak'] = json_encode($images,256);
                    $update['ai_images'] = $images[0];
                    $update['ai_images_arr'] = json_encode($images,256);
                    count($aiImagFaceArrs)==count($images) && $update['ai_image_face_arr_bak'] = json_encode($aiImagFaceArrs,256);
                    count($aiImagFaceArrs)==count($images) && $update['ai_image_face_arr'] = json_encode($aiImagFaceArrs,256);
                    UserNovelChapterPartModel::getInstance()->getWhere(['id'=>$val['id']])->update($update);

                    foreach ($imageData as $image){
                        $image->status=2;
                        $image->user_sn=$val['user_sn'];
                        $image->save();
                    }
                    continue;
                }
            }

            if(empty($val['prompt'])){
                //todo  获取描述词
                try{
                    $prompt = Common::generatedImagePrompt($val['content'],$val['prompt_ai_command']??'');
                }catch (IndexException $e){
                    //失败再试一次
                    if(strpos(strtolower($e->getMessage()),'curl')!==false){
                        $prompt = Common::generatedImagePrompt($val['content'],$val['prompt_ai_command']??'');
                    }else{
                        throw $e;
                    }
                }
                $val->prompt = $prompt;
                $val->save();
                $val['prompt'] = $prompt;
            }

            //todo 根据描述词生成ai漫画图片
            $prompt = $val['prompt'];
            $source = 'user_plan_part_image_save_'.$val['id'];
            $options = [
                'width' => $width, 'height' => $height, 'batch_size' => $imageNums,
                'seed'  => ($val['ai_image_command_seed'] ?: -1), 'command_template_id' => $userPlan['templateid'] ?? 0
            ];
            if(!empty($val['more_people_prompt'])){
                $options['more_people_prompt'] = $val['more_people_prompt'];
            }
            if(!empty($val['refer_image'])){
                $aiImageCommands['init_images'] = [$val['refer_image']];
                $aiImageCommand = json_encode($aiImageCommands,256);
            }
            $requestId = Common::generatedAIImageByTemplate($aiImageCommand,$prompt,$modelVal,$options,$source,$data['requestid']??'');
            $requestIdMap[$requestId] = $val;
        }

        foreach ($requestIdMap as $requestId=>$val){
            while (true){
                $aiImages = Common::getAiImageResult($requestId);
                if(!empty($aiImages) && is_array($aiImages)){
                    $update = [];
                    $update['ai_images_bak'] = $aiImages[0];
                    $update['ai_images_arr_bak'] = json_encode($aiImages,256);
                    $update['ai_images'] = $aiImages[0];
                    $update['ai_images_arr'] = json_encode($aiImages,256);

                    //获取人脸识别数据
                    $aiImageFaceArrs = [];
                    foreach($aiImages as $k=>$image){
                        $aiImageFaceArr = [];
                        $aiImageFaceArr['link'] = $image;
                        $aiImageFaceArr['faceRectangles'] = [];
                        try{
                            $res = DetectFaceAdvance::getInstance()->getFaceBody($image);
                            if(!empty($res['Data']['FaceRectangles'])){
                                $aiImageFaceArr['faceRectangles'] = $res['Data']['FaceRectangles'];
                            }
                        }catch (\Throwable $e){}

                        $aiImageFaceArrs[] = $aiImageFaceArr;

                        //这里加上休眠是因为QPS 5/s
                        sleep(1);
                    }
                    $update['ai_image_face_arr'] = json_encode($aiImageFaceArrs,256);
                    $update['ai_image_face_arr_bak'] = json_encode($aiImageFaceArrs,256);

                    UserNovelChapterPartModel::getInstance()->getWhere(['id'=>$val['id']])->update($update);
                    break;
                }
                sleep(3);

                $first = (new AiImageRequestQueueModel())->getWhere(['requestid'=>$requestId])->first();
                if($first && !empty($first['start_time']) && (time()-strtotime($first['start_time']))>300){
                    throw new IndexException(4020,'生成超时');
                }elseif ($first==false){
                    throw new IndexException(4020,'加入队列失败');
                }
            }
        }
        return true;
    }

    /**
     * 生成失败处理
     * @param $data
     * @param $e
     * @return bool
     * @throws \Throwable
     */
    protected function generatedFail($data,$e)
    {
        try{
            Db::connection('mysql')->beginTransaction();
            $userPlan = UserPromotionPlanModel::getInstance()->find($data['user_planid']);
            $userPlan->finish_time = date('Y-m-d H:i:s');
            $userPlan->status = 3;
            $userPlan->message =mb_substr($e->getMessage(),0,255);
            $userPlan->save();

            //生成失败 退还点数
            $where = [
                'source_table'=>UserPromotionPlanModel::getInstance()->getTable(),
                'sourceid'=>$userPlan['id'],
                'user_sn'=>$userPlan['user_sn'],
            ];
            $consumeId = ConsumePointLogModel::getInstance()->getWhere($where)->value('id');

            if($consumeId){
                $where = [
                    'source_table'=>ConsumePointLogModel::getInstance()->getTable(),
                    'sourceid'=>$consumeId,
                    'user_sn'=>$userPlan['user_sn'],
                    'way'=>2,
                ];
                $first = UserPointFlowModel::getInstance()->getWhere($where)->first();
                if($first){
                    $insert = [];
                    $insert['source_table'] = ConsumePointLogModel::getInstance()->getTable();
                    $insert['sourceid'] = $consumeId;
                    $insert['user_sn'] = $userPlan['user_sn'];
                    $insert['nums'] = abs($first['nums']);
                    $insert['type'] = $first['type'];
                    $insert['way'] = 1;
                    $insert['is_refund'] = 1;
                    UserPointFlowModel::getInstance()->insert($insert);
                }
            }

            Db::connection('mysql')->commit();
        }catch (\Throwable $e){
            Db::connection('mysql')->rollBack();
        }

        return true;
    }

    // 消费失败回调
    /*
    $package = [
        'id' => 1357277951, // 消息ID
        'time' => 1709170510, // 消息时间
        'delay' => 0, // 延迟时间
        'attempts' => 2, // 消费次数
        'queue' => 'send-mail', // 队列名
        'data' => ['to' => 'tom@gmail.com', 'content' => 'hello'], // 消息内容
        'max_attempts' => 5, // 最大重试次数
        'error' => '错误信息' // 错误信息
    ]
    */
    public function onConsumeFailure(\Throwable $e, $package)
    {
//        echo "consume failure\n";
//        echo $e->getMessage() . "\n";
//        // 无需反序列化
//        var_export($package);

        RedisQueue::getInstance()->saveQueue($this->queue,$package['data'],['error'=>$e->getMessage()]);
    }

}